@@ -258,19 +258,27 @@ def __init__(
258
258
raise ValueError ("BusState must be Active or Passive" )
259
259
260
260
if isinstance (timing , BitTimingFd ):
261
- valid_fd_clocks = [
262
- 20000000 ,
263
- 24000000 ,
264
- 30000000 ,
265
- 40000000 ,
266
- 60000000 ,
267
- 80000000 ,
261
+ valid_fd_f_clocks = [
262
+ 20_000_000 ,
263
+ 24_000_000 ,
264
+ 30_000_000 ,
265
+ 40_000_000 ,
266
+ 60_000_000 ,
267
+ 80_000_000 ,
268
268
]
269
- if timing .f_clock not in valid_fd_clocks :
270
- raise CanInitializationError (
271
- f"The PcanBus requires one of the following CAN clocks for CAN FD: "
272
- f"{ ',' .join ([str (f ) for f in valid_fd_clocks ])} (timing={ timing !r} )"
273
- )
269
+ if timing .f_clock not in valid_fd_f_clocks :
270
+ # try setting a valid f_clock. Raise exception if this fails
271
+ for f_clock in reversed (valid_fd_f_clocks ):
272
+ try :
273
+ timing = BitTimingFd (** {** timing , "f_clock" : f_clock })
274
+ break
275
+ except ValueError :
276
+ continue
277
+ else :
278
+ raise CanInitializationError (
279
+ f"The PcanBus requires one of the following CAN clocks for CAN FD: "
280
+ f"{ ',' .join ([str (f ) for f in valid_fd_f_clocks ])} (timing={ timing !r} )"
281
+ )
274
282
self .fd_bitrate = (
275
283
f"f_clock={ timing .f_clock } ,"
276
284
f"nom_brp={ timing .nom_brp } ,"
@@ -287,9 +295,13 @@ def __init__(
287
295
)
288
296
elif isinstance (timing , BitTiming ):
289
297
if timing .f_clock != 8_000_000 :
290
- raise CanInitializationError (
291
- f"The PcanBus requires a 8MHz CAN clock for CAN2.0 (timing={ timing !r} )"
292
- )
298
+ try :
299
+ # try different prescaler values
300
+ timing = BitTiming (** {** timing , "f_clock" : 8_000_000 })
301
+ except ValueError :
302
+ raise CanInitializationError (
303
+ f"The PcanBus requires a 8MHz CAN clock for CAN2.0 (timing={ timing !r} )"
304
+ ) from None
293
305
pcan_bitrate = TPCANBaudrate (timing .btr0 << 8 | timing .btr1 )
294
306
result = self .m_objPCANBasic .Initialize (
295
307
self .m_PcanHandle , pcan_bitrate , hwtype , ioport , interrupt
0 commit comments